using System;
using System.Collections.Generic;
using System.Text;
using ESBSimpleSamples.ServiceClient.Attributes;
using System.Reflection;

namespace ESBSimpleSamples.ServiceClient.Helpers
{
    public static class EnumHelper
    {
        public static string GetName(object enumValue)
        {
            return Enum.GetName(enumValue.GetType(), enumValue);
        }

        public static string GetCode(object enumValue)
        {
            return GetCode(enumValue, true);
        }

        public static string GetCode(object enumValue, bool returnNameIfNoCode)
        {
            string code = null;
            Type enumType = enumValue.GetType();
            FieldInfo info = enumType.GetField(enumValue.ToString());
            object[] attributes = info.GetCustomAttributes(typeof(CodeAttribute), false);
            if (attributes.Length == 1 && attributes[0] is CodeAttribute)
            {
                code = ((CodeAttribute)attributes[0]).Code;
            }
            else if (returnNameIfNoCode)
            {
                code = GetName(enumValue);
            }
            return code;
        }
    }
}
